from mcp.server.fastmcp import FastMCP
from typing import Union
import re

# Create an MCP server
mcp = FastMCP("Katherine Math Server")

@mcp.tool()
def greet(name: str) -> str:
    """打招呼功能\n    Args:\n        name: 用户名\n    Returns:\n        个性化的问候语"""
    return f"您好，{name}！欢迎使用Katherine数学运算服务！"

@mcp.tool()
def add(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """加法运算"""
    return a + b

@mcp.tool()
def subtract(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """减法运算"""
    return a - b

@mcp.tool()
def multiply(a: Union[int, float], b: Union[int, float]) -> Union[int, float]:
    """乘法运算"""
    return a * b

@mcp.tool()
def divide(a: Union[int, float], b: Union[int, float]) -> Union[float, str]:
    """除法运算"""
    try:
        return a / b
    except ZeroDivisionError:
        return "错误: 除数不能为零"

@mcp.tool()
def calculate(expression: str) -> Union[float, str]:
    """四则运算计算器(自动处理优先级)\n    Args:\n        expression: 数学表达式，如'3+5*2'\n    Returns:\n        计算结果或错误信息"""
    try:
        # 使用eval计算表达式，但限制为仅数字和运算符
        if not re.match(r'^[\d\+\-*\/\(\)\.\s]+$', expression):
            return "错误: 表达式包含非法字符"
        return float(eval(expression))
    except Exception as e:
        return f"计算错误: {str(e)}"

if __name__ == "__main__":
    mcp.run(transport="stdio")